package reflection;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @ClassName Demo02
 * @Description TODO
 * 动态操作构造器
 * @Author liang
 * @Date 2018/10/18 10:04
 * @Version 1.0
 **/
public class Demo02 {
    public static void main(String [] args) throws ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException, NoSuchFieldException {
        //动态操作构造器
        String path = "reflection.User";
        Class<User> clazz = (Class<User>) Class.forName(path);
        //通过反射api动态调动构造方法，构造对象
        User user = clazz.newInstance();//调用了user的无参构造方法
        System.out.println(user);

        Constructor<User> c = clazz.getDeclaredConstructor(String.class);//有参构造器
        User liang = c.newInstance("liang");//调用user的有参构造方法
        System.out.println(liang);

        //通过反射api调用普通方法
        Method method = clazz.getDeclaredMethod("say", String.class);
        method.invoke(liang,"hello");//这两行相当于，liang.say("hello");实现了动态调用，方法名和参数都是变量，反射的好处

        //通过反射api操作属性
        Field id = clazz.getDeclaredField("id");
        id.setAccessible(true);//无法操作私有属性,通过这样的模式来跳过检查
        id.set(liang,10);

        System.out.println("操作属性赋值"+liang.getId());


    }
}
